package cn.mothin.frame.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.mothin.frame.core.base.BaseAction;
import cn.mothin.frame.core.interfaces.ILoginUser;
import cn.mothin.frame.core.interfaces.system.ILoginLogHelper;

public class SystemSessionListener implements ServletContextListener,
		HttpSessionAttributeListener {

	private ServletContext servletContext;

	@Override
	public void contextDestroyed(ServletContextEvent servletContextEvent) {

	}

	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		this.servletContext = servletContextEvent.getServletContext();
	}

	@Override
	public void attributeAdded(HttpSessionBindingEvent arg0) {
		if (arg0.getName().equals(BaseAction.LOGIN_SYSTEM_USER_SESSION_ID)) {
			Object obj = arg0.getValue();
			if (obj != null && obj instanceof ILoginUser) {
				ILoginUser loginUser = (ILoginUser) obj;
				WebApplicationContext webApplicationContext = WebApplicationContextUtils
						.getRequiredWebApplicationContext(servletContext);
				ILoginLogHelper loginLogHelper=webApplicationContext.getBean(ILoginLogHelper.class);
				if(loginLogHelper!=null){
					loginLogHelper.recordLogin(loginUser.getSessionId(), loginUser.getId(), loginUser.getLoginIp());
				}
			}
		}

	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent arg0) {
		if (arg0.getName().equals(BaseAction.LOGIN_SYSTEM_USER_SESSION_ID)) {
			Object obj = arg0.getValue();
			if (obj != null && obj instanceof ILoginUser) {
				ILoginUser loginUser = (ILoginUser) obj;
				WebApplicationContext webApplicationContext = WebApplicationContextUtils
						.getRequiredWebApplicationContext(servletContext);
				ILoginLogHelper loginLogHelper=webApplicationContext.getBean(ILoginLogHelper.class);
				if(loginLogHelper!=null){
					loginLogHelper.recordLogout(loginUser.getSessionId(), ILoginLogHelper.LOGOUT_TYPE_OVERTIME);
				}
			}
		}
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent arg0) {

	}

}
